﻿using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
using SDCloudSolution.SDCloud.Web.Infrastructure.Interfaces;

namespace SDCloudSolution.SDCloud.Web.Controllers
{
    [RoutePrefix("modelruns")]
    [Authorize]
    public partial class ModelResultsController : Controller
    {
        private readonly IModelResultViewModelProvider _modelResultViewModelProvider;

        public ModelResultsController(IModelResultViewModelProvider modelResultViewModelProvider)
        {
            _modelResultViewModelProvider = modelResultViewModelProvider;
        }

        [Route("{modelRunId}/results/v1")]
        [HttpGet]
        public virtual async Task<ActionResult> GetResults(int modelRunId)
        {
            if (modelRunId <= 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var result = await _modelResultViewModelProvider.GetModelResultDataAsync(modelRunId);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [Route("{modelRunId}/results/filter/frames/v1")]
        [HttpGet]
        public virtual async Task<ActionResult> GetResultsWithFramePaging(int modelRunId, int framesSkipCount, int framesLimitCount)
        {
            if (modelRunId <= 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            if (framesSkipCount < 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            if (framesLimitCount <= 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var result = await _modelResultViewModelProvider.GetModelResultDataAsync(modelRunId, framesSkipCount, framesLimitCount);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [Route("{modelRunId}/results/filter/time/v1")]
        [HttpGet]
        public virtual async Task<ActionResult> GetResultsWithTimeFilter(int modelRunId, double? timeStart, double? timeEnd)
        {
            if (modelRunId <= 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            if (!timeStart.HasValue && !timeEnd.HasValue)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            if (timeStart.HasValue && timeEnd.HasValue && timeStart.Value > timeEnd.Value)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var result = await _modelResultViewModelProvider.GetModelResultDataAsync(modelRunId, timeStart, timeEnd);

            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}